﻿//   CreateApplication.aspx.cs
//   Copyright (c) 2012 Eswar Prakash
// 
//    This library is free software; you can redistribute it and/or modify  
//    it  under the terms of the GNU Lesser General Public License version  
//    2.1 as published by the Free Software Foundation.                     
//                                                                          
//    This library is distributed in the hope that it will be useful, but   
//    WITHOUT ANY WARRANTY; without even the implied warranty of            
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     
//    Lesser General Public License for more details.                       
//                                                                          
//    You should have received a copy of the GNU Lesser General Public      
//    License along with this library; if not, write to the Free Software   
//    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  
//    USA

namespace CKSAS.AppStorage.ApplicationPages
{
    using System;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebControls;
    using Microsoft.SharePoint.Administration;
    using SharedService;
    using Core.Diagnostics;


    /// <summary>
    /// 
    /// </summary>
    public partial class CreateApplicationPage : LayoutsPageBase
    {
        /// <summary>
        /// databaseSection control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Microsoft.SharePoint.WebControls.ContentDatabaseSection databaseSection;

        /// <summary>
        /// ApplicationPoolSection control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::Microsoft.SharePoint.WebControls.IisWebServiceApplicationPoolSection ApplicationPoolSection;

        /// <summary>
        /// Represents the method that handles the Init event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ((DialogMaster) this.Page.Master).OkButton.Click += new EventHandler(OkButton_Click);
        }

        /// <summary>
        /// Handles the Click event of the OkButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void OkButton_Click(object sender, EventArgs e)
        {
            this.Page.Validate();
            if (this.Page.IsValid)
            {
                var applicationName = this.textApplicationName.Text.Trim();
                SPLongOperation.Begin((x) =>
                                          {
                                              try
                                              {
                                                  // get the database parameters
                                                  var dbParameters =
                                                      SPDatabaseParameters.CreateParameters(
                                                          this.databaseSection.DatabaseName,
                                                          this.databaseSection.DatabaseServer,
                                                          this.databaseSection.DatabaseUserName,
                                                          this.databaseSection.DatabasePassword,
                                                          this.databaseSection.FailoverDatabaseServer,
                                                          SPDatabaseParameterOptions.None);

                                                  // create the application first
                                                  var serviceApplication =
                                                      AppStorageService.Local.CreateApplication(applicationName,
                                                                                               this.ApplicationPoolSection
                                                                                                   .GetOrCreateApplicationPool(),
                                                                                               dbParameters);
                                                  serviceApplication.Update();

                                                  // provision the application
                                                  LoggingUtilities.WriteTraceEntry(DiagnosticsAreas.CKSAS,
                                                      DiagnosticCategories.AppStorageService, TraceSeverity.Medium,
                                                      "Starting provisioning of the service application: {0}",
                                                      serviceApplication.Name);
                                                  serviceApplication.Provision();
                                                  LoggingUtilities.WriteTraceEntry(DiagnosticsAreas.CKSAS,
                                                      DiagnosticCategories.AppStorageService, TraceSeverity.Medium,
                                                      "Successfully provisioned the service application: {0}",
                                                      serviceApplication.Name);

                                                  // now create the proxy
                                                  var appProxy =
                                                      AppStorageService.Local.CreateApplicationProxy(applicationName,
                                                                                                    serviceApplication);
                                                  appProxy.Update();
                                                  appProxy.Provision();

                                                  // add to default proxy group
                                                  SPServiceApplicationProxyGroup.Default.Add(appProxy);
                                                  SPServiceApplicationProxyGroup.Default.Update();
                                              }
                                              catch (Exception ex)
                                              {
                                                  LoggingUtilities.WriteEventEntry(DiagnosticsAreas.CKSAS,
                                                      DiagnosticCategories.AppStorageService,
                                                      EventSeverity.Error, ex, "Service Application: {0}",
                                                      applicationName);
                                                  throw;
                                              }
                                              x.EndScript("window.frameElement.commonModalDialogClose(1, null);");
                                          });
            }
        }

        /// <summary>
        /// Represents that method that handles the <see cref="E:System.Web.UI.Control.Load"/> event of the page.
        /// </summary>
        /// <param name="e">A <see cref="T:System.EventArgs"/> that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // provide some default values for the controls
            if (!this.Page.IsPostBack)
            {
                //this.textApplicationName.Text = "Auto Numbering Service Application 1";
                //this.databaseSection.DatabaseName = "AutoNumberingServiceDatabase_" + Guid.NewGuid().ToString("N");
            }
        }
    }
}